﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Net;

namespace DZPK.SocketImpl
{
    class SocketWrapper
    {
        //private TcpClient clientSocket;
        public Socket sender;
        private bool bConnected;
        private ByteArray resBytes;
        private static int resSize = 10240;

        public Endian endian;

        public uint bytesAvailable;

        public SocketWrapper()
        {
            sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            bConnected = false;
        }

        public void connect(string ip, int port)
        {
            IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse(ip), port);

            sender.Connect(remoteEP);

            bConnected = true;
        }

        public int readBytes(ByteArray bytes, uint length = 0)
        {
            int resLen = 0;

            if (length == 0)
            {
                throw new NotImplementedException();
            }
            else 
            {
                byte[] arr = new byte[length];
                resLen = sender.Receive(arr, (int)length, SocketFlags.None);
                bytes.writeArrayBytes(arr);
            }

            return resLen;
        }

        public void writeBytes(ByteArray bytes, uint offset = 0, uint length = 0)
        {
            if (offset != 0)
            {
                throw new NotImplementedException();
            }

            if (length == 0)
            {
                length = bytes.length;
            }

            resBytes = new ByteArray();
            resBytes.writeBytes(bytes);
        }

        public void flush()
        {
            byte[] sendbyte = resBytes.GetByteArrayData();
            sender.Send(sendbyte);
        }

        public void close()
        {
            sender.Close();
        }

    }
}
